<?php
//define('COOKIELOCAL', str_replace('\\', '/', realpath('../')) . '/' . 'cookies_cnpjs/');
define('COOKIELOCAL', str_replace('\\', '/', realpath('../')) . '/' . 'cookies_receita_federal/');
@session_start();

$cookieFile = COOKIELOCAL . session_id();

// cria arquivo onde será salva a sessão com a receita
if (!file_exists($cookieFile)) {
    $file = fopen($cookieFile, 'w');
    fclose($file);
}

$url = 'http://www.receita.fazenda.gov.br/Aplicacoes/ATSPO/Certidao/gerarCaptcha.asp?app=CNDConjuntaInter&t=1429712208879';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

$imgsource = curl_exec($ch);
curl_close($ch);

$saveto = '../images/image.png';

if (file_exists($saveto)) {
    unlink($saveto);
}

$fp = fopen($saveto, 'x');
fwrite($fp, $imgsource);
fclose($fp);
?>
<html>
    <head>
        <title>CNPJ e Captcha</title>
    </head>
    <body>
      <?php include_once 'carregando.php' ; ?>
    <form name="emitirCND" id="emitirCND" method="post" action="<?php echo base_url('index.php/certidoes/processa_receita_federal') ?>">
        <p>
            <input type="hidden" name="NI" value="<?php echo $pessoa->pessoas_cnpj ?>"  />               
            <?php
            $objCaptcha = new Captcha_Model();
            $objCaptcha->setFileName($saveto);
            ?>
            <input type="hidden" name="txtTexto_captcha_serpro_gov_br" maxlength="6" value="<?php $objCaptcha->submeterCaptcha(); ?>" required  />
        </p>
        <p>
        </p>
    </form>
</html>

<script>
    document.getElementById("emitirCND").submit();
</script>